package service

import (
	"fmt"
	"net/http"

	"gitee.com/chenxuan520/npyhomework/internal/config"
	"gitee.com/chenxuan520/npyhomework/internal/model"
	"gitee.com/chenxuan520/npyhomework/internal/util"
	"github.com/gin-gonic/gin"
)

type OperType int8

const (
	StopRecv  OperType = 0
	BeginRecv OperType = 1
	UpLight   OperType = 2
	DownLight OperType = 3
)

func Login(c *gin.Context) {
	type LoginInfo struct {
		Password string `json:"password"`
	}
	info := LoginInfo{}
	err := c.BindJSON(&info)
	if err != nil {
		Error(c, http.StatusBadRequest, err.Error())
		return
	}
	if info.Password != config.GlobalConfig.Server.Password {
		Error(c, http.StatusBadRequest, "密码错误")
		return
	}
	_, err = util.CreateJwt("temp")
	if err != nil {
		Error(c, http.StatusBadRequest, err.Error())
		return
	}
	Success(c, "/dist/data.html")
}

func GetData(c *gin.Context) {
	type DataInfo struct {
		ID    int64 `json:"id"`
		Limit int64 `json:"limit"`
	}
	info := DataInfo{}
	err := c.BindJSON(&info)
	if err != nil {
		fmt.Println(err)
		Error(c, http.StatusBadRequest, "invalue jwt")
		return
	}
	result, err := model.GetDataByIDRange(info.ID, info.Limit)
	if err != nil {
		fmt.Println(err)
		Error(c, http.StatusBadRequest, err.Error())
		return
	}
	Success(c, result)
}

func UpdateMicroComputer(c *gin.Context) {
	type OperInfo struct {
		Type OperType `json:"type"`
	}
	info := OperInfo{}
	err := c.BindJSON(&info)
	if err != nil {
		fmt.Println(err)
		Error(c, http.StatusBadRequest, "invalue jwt")
		return
	}
	err = GlobalConfig.WriteOper(info.Type)
	if err != nil {
		fmt.Println(err)
		Error(c, http.StatusBadRequest, "invalue jwt")
		return
	}
	Success(c, nil)
}

func UpdateSql(c *gin.Context) {
	// TODO:有安全风险,但是懒得弄了
	type SqlInfo struct {
		Sql string `json:"sql"`
	}
	info := SqlInfo{}
	err := c.BindJSON(&info)
	if err != nil {
		fmt.Println(err)
		Error(c, http.StatusBadRequest, "invalue jwt")
		return
	}
	fmt.Println(info)
	err = model.RunSql(info.Sql)
	if err != nil {
		fmt.Println(err)
		Error(c, http.StatusBadRequest, "invalue jwt")
		return
	}
	Success(c, nil)
}
